import React, { useState,useRef,forwardRef,useImperativeHandle,useContext,useEffect } from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { message, Upload } from 'antd';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import { current } from '@reduxjs/toolkit';
import store from '@/store';

const getBase64 = (img: RcFile, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};
const onPreview = async (file: UploadFile) => {
  let src = file.url as string;
  if (!src) {
    src = await new Promise((resolve) => {
      const reader = new FileReader();
      reader.readAsDataURL(file.originFileObj as RcFile);
      reader.onload = () => resolve(reader.result as string);
    });
  }
}
const beforeUpload = (file: RcFile) => {
  // let  gift = useContext(context)
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};
type Iprops = {
  uploadUrl: (c: any) => void
  ref:any
}
const UploadCom: React.FC<Iprops> =forwardRef((props,ref)=>{

    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();
    let { uploadUrl } = props

    let data = store.getState()
    
    useEffect(()=>{
      setImageUrl(data.product)
    })
    
    
    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
      console.log(info);
      
      if (info.file.status === 'uploading') {
        setLoading(true);
        return;
      }
      if (info.file.status === 'done') {
        // console.log(info.file);
        // Get this url from response in real world.
        getBase64(info.file.originFileObj as RcFile, (url) => {
          setLoading(false);
          uploadUrl(url);
          setImageUrl(url);
          store.dispatch({type:'IMAGE',payload:url})
        });
      }
    };
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );
    // let ElementCom = ()=>{
    //     if(imageUrl){
    //       return <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
    //     }else{
    //       return uploadButton
    //     }
    // }
    useImperativeHandle(ref,()=>{
      return {
        getFocus(a:any){
          setImageUrl(a)
          return true
        }
      }
    })
    return (
  
        <Upload
          // key={Math.random()}
          name="headimgurl"
          listType="picture-card"
          className="avatar-uploader"
          showUploadList={false}
          action="/api/students/uploadStuAvatar"
          beforeUpload={beforeUpload}
          onChange={handleChange}
          onPreview={onPreview}
        >
          {/* <button onClick={handleDel}>点击</button> */}
          {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
            {/* {
              ElementCom()
            } */}
        </Upload>
  
    );
  
})

export default UploadCom;